Object.defineProperty(exports, "__esModule", {
    value: !0
}), exports.setDefaultParams = setDefaultParams, exports.listenToken = listenToken, 
exports.registerToken = registerToken, exports.getTokens = getTokens, exports.getTokensSync = getTokensSync, 
exports.updateTokens = updateTokens, exports.getWxLoginCode = getWxLoginCode, exports.getLoginCodeOrSessionkey = getLoginCodeOrSessionkey, 
exports.default = exports.api = void 0;

var _promise = _interopRequireDefault(require("./promise.js")), _util = _interopRequireDefault(require("./util.js")), _eventEmitter = _interopRequireDefault(require("./event-emitter")), _apiCode = _interopRequireDefault(require("./api-code.js")), _host = require("./host.js"), _request = require("./request.js");

function _interopRequireDefault(e) {
    return e && e.__esModule ? e : {
        default: e
    };
}

function _objectSpread(t) {
    for (var e = 1; e < arguments.length; e++) {
        var n = null != arguments[e] ? arguments[e] : {}, o = Object.keys(n);
        "function" == typeof Object.getOwnPropertySymbols && (o = o.concat(Object.getOwnPropertySymbols(n).filter(function(e) {
            return Object.getOwnPropertyDescriptor(n, e).enumerable;
        }))), o.forEach(function(e) {
            _defineProperty(t, e, n[e]);
        });
    }
    return t;
}

function _defineProperty(e, t, n) {
    return t in e ? Object.defineProperty(e, t, {
        value: n,
        enumerable: !0,
        configurable: !0,
        writable: !0
    }) : e[t] = n, e;
}

var RETRY_MAX = 3, RETRY_INVERTER = 2e3, GETTOKENS_EVENT_KEY = "user.get.token", REGISTER_ACTION_KEY = "register", LOGIN_ACTION_KEY = "login", tokens = {}, loginKey = {
    key: "loginkey",
    get: function() {
        return wx.getStorageSync(this.key);
    },
    set: function(e) {
        e !== this.get() && wx.setStorage({
            key: this.key,
            data: e
        });
    },
    remove: function() {
        wx.removeStorageSync(this.key);
    }
}, defaultParams = {}, api = {
    login: function(e) {
        return (0, _request.post)("".concat(_host.apiPrefix, "/weapp/loginv2"), e);
    },
    register: function(e) {
        return (0, _request.post)("".concat(_host.apiPrefix, "/weapp/register"), e);
    },
    deviceInfo: function(e) {
        return (0, _request.post)("".concat(_host.apiPrefix, "/weapp/deviceinfo"), e);
    }
};

exports.api = api;

var regParams, tokensPromise = null;

function setDefaultParams(e) {
    Object.assign(defaultParams, e);
}

function listenToken(e) {
    _eventEmitter.default.addListener(GETTOKENS_EVENT_KEY, e);
}

function registerToken(t) {
    wx.showLoading({
        title: "登录中...",
        mask: !0
    });
    var e = wx.hideLoading;
    regParams = t;
    var n = getLoginCodeOrSessionkey().then(function(e) {
        return api.register(_objectSpread({}, defaultParams, e, t));
    });
    return n.then(function(e) {
        return tokensPromise = _promise.default.resolve(e.data);
    }), n.then(e, e), n.then(function(e) {
        return handleGetTokens(e, REGISTER_ACTION_KEY);
    }).catch(handleGetTokensError);
}

function getTokens(e, t) {
    if (!tokensPromise) {
        wx.showLoading({
            title: "登录中..."
        });
        var n = loginKey.get(), o = function() {
            wx.hideLoading(), postDeviceInfo();
        }, r = n ? getAccessToken({
            loginkey: n
        }) : getLoginCodeOrSessionkey().then(function(e) {
            return getAccessToken(e);
        });
        r.then(o, o), tokensPromise = r.then(function(e) {
            return handleGetTokens(e, LOGIN_ACTION_KEY);
        }).catch(handleGetTokensError);
    }
    return tokensPromise.then(e, t), tokensPromise;
}

function getTokensSync() {
    return tokens;
}

function updateTokens(e) {
    var t = e.accesstoken, n = e.avatar, o = e.loginkey, r = e.openid, s = e.realname, i = e.uid, a = e.unionid, u = e.userid, c = e.corpid, f = e.isverifymobile, l = e.sessionkey;
    Object.assign(tokens, {
        accesstoken: t,
        avatar: n,
        loginkey: o,
        openid: r,
        realname: s,
        uid: i,
        unionid: a,
        userid: u,
        corpid: c,
        isverifymobile: f,
        sessionkey: l
    }), o && loginKey.set(o);
    try {
        t && _eventEmitter.default.emit(GETTOKENS_EVENT_KEY, tokens);
    } catch (e) {
        console.error(e);
    }
}

function getAccessToken(e) {
    var t = _objectSpread({}, defaultParams, {
        code: ""
    }, e);
    return api.login(t);
}

function getWxLoginCode() {
    return new _promise.default(function(n, e) {
        wx.login({
            success: function(e) {
                var t = e.code;
                return n({
                    code: t
                });
            },
            fail: e
        });
    });
}

function getLoginCodeOrSessionkey() {
    return new _promise.default(function(e, t) {
        wx.checkSession({
            success: function() {
                console.log("session effective"), tokens.sessionkey ? e({
                    sessionkey: tokens.sessionkey
                }) : getWxLoginCode().then(e, t);
            },
            fail: function() {
                tokens.sessionkey = "", getWxLoginCode().then(e, t);
            }
        });
    });
}

function retry(n, o) {
    return new _promise.default(function(e, t) {
        n ? setTimeout(function() {
            return e(o());
        }, RETRY_INVERTER) : t();
    });
}

var getTokensRetryCount = 0;

function retryGetTokens() {
    return loginKey.remove(), tokensPromise = null, retry((getTokensRetryCount += 1) < RETRY_MAX, function() {
        return getTokens();
    });
}

var registerRetryCount = 0;

function retryRegister(e) {
    var t = (registerRetryCount += 1) < RETRY_MAX;
    return console.log(t, "注册"), retry(t, function() {
        return registerToken(e);
    });
}

function handleGetTokens(e, t) {
    var n = _util.default.clearBOMAndParseJson(e), o = n.code, r = n.data, s = n.message;
    switch (o) {
      case _apiCode.default.SUCCESS:
      case _apiCode.default.NO_BINDING_USER:
      case _apiCode.default.MOBILE_IS_NOT_VERIFY:
        if (!r) throw new Error("api:".concat(t, ":fail no data"));
        return updateTokens(Object.assign({}, tokens, r)), _promise.default.resolve(tokens);

      case _apiCode.default.USER_ACCOUNT_NOT_EXISTS:
        return updateTokens(r), _promise.default.resolve();

      case _apiCode.default.USER_ACCOUNT_ALREADY_EXISTS:
        tokens.sessionkey = "";

      case _apiCode.default.TOKEN_EXPIRY:
      case _apiCode.default.PARAM_MISSING:
        return retryGetTokens().catch(function(e) {
            throw new Error("api:".concat(t, ":fail ").concat(o, " ").concat(s));
        });

      case _apiCode.default.SESSIONKEY_EXPIRY:
        return tokens.sessionkey = "", (t === LOGIN_ACTION_KEY ? retryGetTokens() : retryRegister(regParams)).catch(function() {
            throw new Error("api:".concat(t, ":fail ").concat(o, " ").concat(s));
        });

      default:
        throw new Error("api:".concat(t, ":fail ").concat(o, " ").concat(s));
    }
}

var failModal = !0;

function handleGetTokensError(e) {
    var t = e.errMsg, n = e.message;
    return tokensPromise = null, failModal && (failModal = !1, registerRetryCount = getTokensRetryCount = 0, 
    wx.showModal({
        title: "微信登录失败",
        content: "请尝试重新打开小程序，或联系客服解决(错误原因：".concat(t || n, ")"),
        complete: function() {
            return failModal = !0;
        }
    })), _promise.default.reject(e);
}

function postDeviceInfo(e) {
    var n = "last_post_device_info_time", t = wx.getStorageSync(n);
    (!t || 864e5 < Date.now() - t) && wx.getNetworkType({
        success: function(e) {
            var t = e.networkType;
            wx.getSystemInfo({
                success: function(e) {
                    wx.setStorage({
                        key: n,
                        data: Date.now()
                    }), api.deviceInfo(_objectSpread({
                        networkType: t
                    }, e));
                }
            });
        }
    });
}

var _default = {
    api: api,
    listenToken: listenToken,
    registerToken: registerToken,
    setDefaultParams: setDefaultParams,
    getTokens: getTokens,
    getTokensSync: getTokensSync,
    updateTokens: updateTokens,
    getWxLoginCode: getWxLoginCode,
    getLoginCodeOrSessionkey: getLoginCodeOrSessionkey
};

exports.default = _default;